import { host } from "./config";

/**
 * 请求封装
 * @param method 
 * @param pathname 
 * @param data 
 * @param options 
 * @returns 
 */
export async function request(
  method: requestMethods = "GET",
  pathname: string,
  data: BaseObj = {},
  options: {
    mode?: "no-cors" | "cors" | "same-origin"
    headers?: any
  } = {
    headers: {
      'Content-Type':'application/json'
    }
  }
) {
  const href = pathname.startsWith('http') ? pathname : `${host}${pathname}`;
  const url = method === "GET" ? `${href}${Object.keys(data).length?'?':''}${json2query(data)}` : href;

  return fetch(url, {
    ...options,
    method,
    [method === "GET" ? "" : "body"]: JSON.stringify(data),
  }).then(async res => {
    if (!res.ok) {
      console.log('请求失败', res);
      window.kchValidator?.handleHttpError({
        url,
        method,
        message: res.statusText,

        data,
        status: res.status,
      });
    }
    console.log(res);
    const response = await res.json();
    if (response.success === false) {
      console.log('请求数据异常', response);
      window.kchValidator?.handleHttpError({
        url,
        method,
        message: response.msg,

        data,
        code: response.code,
      });
    }
    return response;
  }).catch(error => {
    console.log('请求异常', error);
    window.kchValidator?.handleHttpError({
      url,
      method,
      message: error,

      data,
    });
  })
}

/**
 * json转url查询参数
 * 会去除值为undefined的key
 */
export function json2query(json: BaseObj) {
  if (!json) return ''
  return Object.keys(json).map(key => {
    if (json[key] === undefined) return '';
    return `${encodeURIComponent(key)}=${encodeURIComponent(json[key])}`;
  }).filter(Boolean).join('&')
}